package ximage

import (
	"errors"
	"image"
	"image/color"
	"os"
	"path/filepath"
)

//Thumbnial生成缩略图相关信息封装
type Thumbnail struct {
	//原始图片文件名
	SrcImageFileName string
	//生成缩略图片文件名
	DestImageFileName string
	//生成缩略图片宽
	DestImageWidth int
	//生成缩略图片高
	DestImageHeight int
}

//DrawThumbnail生成缩略图
func (this *Thumbnail) DrawThumbnail() error {
	srcFile, err := os.Open(this.SrcImageFileName)
	if err != nil {
		return err
	}
	defer srcFile.Close()
	m, _, err := image.Decode(srcFile)
	if err != nil {
		return err
	}

	destImageFile, err := os.Create(this.DestImageFileName)
	if err != nil {
		return err
	}
	defer destImageFile.Close()

	if this.DestImageWidth <= 0 || this.DestImageHeight <= 0 {
		return errors.New("DestImageWidth and DestImageHeight value must be positive number.")
	}
	var thumbnailImage = image.NewNRGBA(image.Rect(0, 0, this.DestImageWidth, this.DestImageHeight))

	var bounds = m.Bounds()
	var curW, curH = bounds.Dx(), bounds.Dy()

	if curW <= 0 || curH <= 0 {
	} else {
		for y := 0; y < this.DestImageHeight; y++ {
			for x := 0; x < this.DestImageWidth; x++ {
				subX := x * curW / this.DestImageWidth
				subY := y * curH / this.DestImageHeight
				r32, g32, b32, a32 := m.At(subX, subY).RGBA()
				r := uint8(r32 >> 8)
				g := uint8(g32 >> 8)
				b := uint8(b32 >> 8)
				a := uint8(a32 >> 8)
				thumbnailImage.SetNRGBA(x, y, color.NRGBA{R: r, G: g, B: b, A: a})
			}
		}
	}

	ext := filepath.Ext(this.DestImageFileName)
	if dofunc, ok := writeImageFunMap[ext]; ok {
		return dofunc(destImageFile, thumbnailImage)
	} else {
		return fileExtNotSupport
	}
}
